#!/usr/bin/env bash
# Generate work script used to deploy on remote host

while getopts :f:n:h opt
do case "$opt" in
    f) fn=$OPTARG ;;
	h)  echo
		echo "Usage: sync-template [-f] <template_file> [-n] <pbs_script.pbs>"
        echo ">>> template_file: file used to generate pbs template, must be a shell script contains qsub_header."
        echo ">>>                If not specified, a default templated will be used."
        echo ">>> pbs_script.pbs: pbs file generated from template_file, if not specified, a default name will be given."
        echo ">>>"
        echo ">>> examples:"
        echo "              sync-template # this will use default template and output filename."
        echo "         or"
        echo "              sync-template -f my_template -n my_job.pbs   #  this will use custom template and output filename."
        echo
        exit ;;
    n) pn=$OPTARG ;;
	*) echo "Unknown option: $opt"
		echo
		sync-template -h
        exit ;;
	esac
done


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# if work script not specified, use work.sh as default
if [ ! -n "$fn" ]; then
    if [ ! -n "$pn" ]; then
        cat $DIR/qsub_header $DIR/commands > $(pwd)/work_script.pbs
        chmod u+x $(pwd)/work_script.pbs
    else
        cat $DIR/qsub_header $DIR/commands > $(pwd)/$pn
    fi
else
#    cat $DIR/qsub_header $DIR/commands > $DIR/$1
#    chmod u+x $DIR/$1
    if [ -r "$fn" ]; then
        if [ ! -n "$pn" ]; then
            cat $fn > $(pwd)/work_script.pbs
        else
            cat $fn > $(pwd)/$pn
        fi
    else
        echo ">>> file $fn does not exist"
        echo ">>> exit..."
    fi
fi


